﻿/// <reference path="/common/js/jquery-1.10.2.min.js" />
/// <reference path="../js/imagesloaded-3.1.4.min.js" />
/// <reference path="../js/jquery.slides.min.js" />
/// <reference path="../js/masonry-3.1.5.min.js" />
/// <reference path="iAjax-1.0.src.js" />

var iUtility = (function () {
    var _loadControl = function (fullPath, data, success) {
        if (typeof (data) == "function") {
            success = data;
            data = {};
        }
        data.Action = "UCRender";
        data.FullPath = fullPath;
        iAjax.post(
            "/handle/RenderHandler.ashx",
            data,
            success
        );
    }

    var _imageCenter = function (selector, imageContainer, overflow) {
        var images = $(selector + " img[center!='center']");
        var containers = imageContainer ? images.parents(imageContainer) : images.parent();
        containers.css("position", "relative");
        containers.css("overflow", overflow ? overflow : "hidden");
        images.css("position", "absolute");
        //images.load(function(){
        //    imagecenterprocess(this, imageContainer);
        //})
        images.each(function(index, img){
            $(img).load(function(){
                imagecenterprocess(img, imageContainer);
            })
            img.src = img.src + "v=" + Math.random();
        })
        //imagesLoaded(selector, function (a) {
        //    images.each(function (index, image) {
        //        imagecenterprocess(image, imageContainer);
        //    });
        //});
        $(selector).show();
    }
    function imagecenterprocess(image, imageContainer) {
        $(image).width("auto");
        $(image).height("auto");
        var box = $(image).parents(imageContainer);
        var scaling = $(image).width() / $(image).height();
        var zoomHeight = box.width() / scaling;
        if (zoomHeight > box.height()) {
            $(image).width(box.width());
            $(image).css("top", (0 - ($(image).height() - box.height()) / 2) + "px");
            $(image).css("left", 0);
        } else {
            $(image).height(box.height());
            $(image).css("top", 0);
            $(image).css("left", (0 - ($(image).width() - box.width()) / 2) + "px");
        }
        $(image).attr("center", "center");
    }
    
    var _masonry = function (selector, itemSelector) {
        var msnry = new Masonry(selector, { "itemSelector": itemSelector });
        msnry.layout();
    }

    var _loadEmotion = function (url, textbox, callback) {
        $.get(
            url,
            function (data) {
                var $container = $("[data-part='emotion']");
                $container.html(data);
                var height = _getHeight($(".expreBox"));

                //选择表情
                $("#exp_emo0 a").click(function (e) {
                    var textbox = $("[data-emotion]");
                    var emotion = $(this).attr("title");
                    if (emotion == undefined || emotion == "") {
                        textbox.val(textbox.val().replace(/\[[^\]]*\]$/, ""));
                    } else {
                        textbox.val(textbox.val() + "[" + emotion + "]");
                    }
                    e.stopPropagation();
                });
                var mySwiper = new Swiper(".expreBox", {
                    pagination: ".pNumCon"
                });
                $container.hide().removeClass("emotion-hidden");
                //回调
                callback && callback();
            }
        );
    }

    $.fn.focusEnd = function () {
        _moveCursorToEnd(this);
    }

    var _moveCursorToEnd = function (obj) {
        if (!(obj && obj.value)) return;
        var len = obj.value.length;
        if (document.selection) {
            var sel = obj.createTextRange();
            sel.moveStart('character', len);
            sel.collapse();
            sel.select();
        } else if (typeof obj.selectionStart == 'number' && typeof obj.selectionEnd == 'number') {
            obj.selectionStart = obj.selectionEnd = len;
        }
    }

    var _fastClick = function () {
        window.addEventListener("load", function () {
            FastClick.attach(document.body);
        }, false);
    }

    var _Android = function () {
        return /android/i.test(navigator.userAgent);
    }

    var _iPhone = function () {
        return /iphone/i.test(navigator.userAgent);
    }

    var _appendShade = function (setting) {
        var options = {
            zindex: 9998,
            opacity: 0.5,
            backgroundcolor: "#000"
        };
        $.extend(options, setting);
        $(document.body).prepend('<div id="iutility_shade_layer" style="top:-50%;left:0;width:100%;height:200%;position:fixed;z-index:' + options.zindex + ';background-color:' + options.backgroundcolor + ';opacity:' + options.opacity + ';"></div>');
    }

    var _removeShade = function () {
        $("#iutility_shade_layer").remove();
    }

    var _readAsDataURL = function (file, onloadevent) {
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function () {
            onloadevent(this.result);
        };
    }

    var _htmlEncode = function (text) {
        return text.replace(/&/g, '&amp').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    }

    var _htmlDecode = function (text) {
        return text.replace(/&amp;/g, '&').replace(/&quot;/g, '/"').replace(/&lt;/g, '<').replace(/&gt;/g, '>');
    }

    var _lazyLoad = function (setting) {
        var options = {
            container: "",
            offsetHeight: 0
        };
        $.extend(options, setting || {});
        var status = 0;
        setImageSize(options);
        setImageSrc(options); //页面加载时滚动条未滚动，加载浏览器可见区域的图片
        window.onscroll = function () {
            if (setting.scroll) {
                setting.scroll();
            }
            if (status == 1) return;
            status = 1;
            if (getImages(options).length == 0) return;
            setTimeout(function () {
                setImageSrc(options);
                status = 0;
            }, 300)
        };
        function getImages(options) {
            return $("#" + options.container + " img[data-loaded!=1]");
        }
        function setImageSize(options) {
            getImages(options).each(function (index, item) {
                var _this = $(this);
                var width = parseInt(_this.attr("width"));
                var height = parseInt(_this.attr("height"));
                var maxWidth = parseInt(_this.css("max-width").replace("px", ""));
                var size = width > maxWidth ? _zoomSize(width, height, maxWidth) : { width: width, height: height };
                _this.attr("width", size.width);
                _this.attr("height", size.height);
            });
        }
        function setImageSrc(options) {
            var images = getImages(options);
            var browserPosition = document.documentElement.clientHeight + $(window).scrollTop() + options.offsetHeight;
            images.each(function (item) {
                var _this = $(this);
                var imagePosition = _this.offset().top;
                if (imagePosition > browserPosition) return;
                _this.attr("src", _this.attr("data-src"));
                _this.attr("data-loaded", 1);
            });
        }
    }

    var _getTimeSpan = function (startDate, endDate) {
        var timespan_ms = startTime.getTime() - endTime.getTime();
        var timespan = new TimeSpan();

        //距离结束日期的天数
        timespan.Days = Math.floor(timespan_ms / (1000 * 60 * 60 * 24));
        var days_remaining = timespan_ms % (1000 * 60 * 60 * 24);
        //距离结束日期天数之后的小时数
        timespan.Hours = Math.floor(days_remaining / (1000 * 60 * 60));
        var hours_remaining = days_remaining % (1000 * 60 * 60);
        //距离结束日期天数，小时数之后的分钟数
        timespan.Minutes = Math.floor(hours_remaining / (60 * 1000));
        var minutes_remaining = hours_remaining % (60 * 1000);
        //距离结束日期天数，小时数，分钟数之后的秒数
        timespan.Seconds = Math.round(hours_remaining / 1000);

        timespan.TotalSeconds = Math.floor(timespan_ms / 1000);
        timespan.TotalMinutes = Math.floor(timespan_ms / (1000 * 60));
        timespan.TotalHours = Math.floor(timespan_ms / (1000 * 60 * 60));
        timespan.TotalDays = Math.floor(timespan_ms / (1000 * 60 * 60 * 24));

        return timespan;
    }

    var TimeSpan = function () {
        return {
            Seconds: 0,
            Minutes: 0,
            Hours: 0,
            Days: 0,
            TotalSeconds: 0,
            TotalMinutes: 0,
            TotalHours: 0,
            TotalDays: 0
        }
    }

    var _zoomSize = function (width, height, newWidth) {
        var scaling = width / height;
        var newHeight = newWidth / scaling;
        return { "width": newWidth, "height": newHeight };
    }

    var _getHeight = function (el) {
        var $el = $(el);
        $(document.head).append("<style id='getHeight'>.get-height{ position:absolute; visibility: hidden; display: block; }</style>");
        var height = $(el).height();
        $("#getHeight").remove();
        return height;
    }

    return {
        LoadControl: _loadControl,
        //Rebind: _rebind,
        ImageCenter: _imageCenter,
        MasonryLayout: _masonry,
        LoadEmotion: _loadEmotion,
        FastClick: _fastClick,
        Android: _Android,
        iPhone: _iPhone,
        AppendShade: _appendShade,
        RemoveShade: _removeShade,
        ReadAsDataURL: _readAsDataURL,
        HtmlEncode: _htmlEncode,
        HtmlDecode: _htmlDecode,
        LazyLoad: _lazyLoad,
        GetTimeSpan: _getTimeSpan,
        ZoomSize: _zoomSize
    }
})();

var Emotion = (function () {
    var _data = {
        "[微笑]":"e100",
        "[撇嘴]":"e101",
        "[色]"  :"e102",
        "[发呆]":"e103",
        "[得意]":"e104",
        "[流泪]":"e105",
        "[害羞]":"e106",
        "[闭嘴]":"e107",
        "[睡]"  :"e108",
        "[大哭]":"e109",
        "[尴尬]":"e110",
        "[发怒]":"e111",
        "[调皮]":"e112",
        "[呲牙]":"e113",
        "[惊讶]":"e114",
        "[难过]":"e115",
        "[酷]"  :"e116",
        "[冷汗]":"e117",
        "[抓狂]":"e118",
        "[吐]"  :"e119",
        "[偷笑]":"e120",
        "[可爱]":"e121",
        "[白眼]":"e122",
        "[傲慢]":"e123",
        "[饥饿]":"e124",
        "[困]"  :"e125",
        "[惊恐]":"e126",
        "[流汗]":"e127",
        "[憨笑]":"e128",
        "[大兵]":"e129",
        "[奋斗]":"e130",
        "[咒骂]":"e131",
        "[疑问]":"e132",
        "[嘘..]":"e133",
        "[晕]"  :"e134",
        "[折磨]":"e135",
        "[衰]"  :"e136",
        "[骷髅]":"e137",
        "[敲打]":"e138",
        "[再见]":"e139",
        "[擦汗]":"e140",
        "[抠鼻]":"e141",
        "[鼓掌]":"e142",
        "[溴大了]": "e143",
        "[坏笑]":"e144",
        "[左哼哼]": "e145",
        "[右哼哼]": "e146",
        "[哈欠]":"e147",
        "[鄙视]":"e148",
        "[委屈]":"e149",
        "[快哭了]": "e150",
        "[阴险]":"e151",
        "[亲亲]":"e152",
        "[吓]"  :"e153",
        "[可怜]":"e154",
        "[菜刀]":"e155",
        "[西瓜]":"e156",
        "[啤酒]":"e157",
        "[篮球]":"e158",
        "[乒乓]":"e159",
        "[咖啡]":"e160",
        "[饭]"  :"e161",
        "[猪头]":"e162",
        "[玫瑰]":"e163",
        "[凋谢]":"e164",
        "[示爱]":"e165",
        "[爱心]":"e166",
        "[心碎]":"e167",
        "[蛋糕]":"e168",
        "[闪电]":"e169",
        "[炸弹]":"e170",
        "[刀]"  :"e171",
        "[足球]":"e172",
        "[瓢虫]":"e173",
        "[便便]":"e174",
        "[月亮]":"e175",
        "[太阳]":"e176",
        "[礼物]":"e177",
        "[拥抱]":"e178",
        "[强]"  :"e179",
        "[弱]"  :"e180",
        "[握手]":"e181",
        "[胜利]":"e182",
        "[抱拳]":"e183",
        "[勾引]":"e184",
        "[拳头]":"e185",
        "[差劲]":"e186",
        "[爱你]":"e187",
        "[NO]"  :"e188",
        "[OK]"  :"e189",
        "[爱情]":"e190",
        "[飞吻]":"e191",
        "[跳跳]":"e192",
        "[发抖]":"e193",
        "[怄火]":"e194",
        "[转圈]":"e195",
        "[磕头]":"e196",
        "[回头]":"e197",
        "[跳绳]":"e198",
        "[挥手]":"e199"
    }
    var _replace = function (content, path) {
        var regex = /(\[.*?\])/;
        path = path ? path : "/common/emotion/mp/";
        while (regex.test(content)) {
            var mt = content.match(regex)[0];
            content = content.replace(regex, "<img class='emotion-image' src='" + path + _data[mt] + ".gif' />");
        }
        return content;
    }
    return {
        replace: _replace
    }
})();